package com.okq.action;

import com.okq.action.base.BaseActionSupport;
import com.okq.entity.Log;
import com.okq.entity.User;
import com.okq.service.ILogService;
import com.okq.service.IRoleService;
import com.okq.util.BaseTool;
import com.okq.util.PublicClass;
import com.okq.util.TimeTool;
import com.okq.util.page.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述 : 系统日志Action
 * 作者 : zdl
 * 日期 : 2017/7/5 9:47
 */
public class LogAction extends BaseActionSupport {
    private static final long serialVersionUID = 2954521399420163535L;
    /**
     * 系统日志接口
     */
    @Autowired
    private ILogService logServiceImpl;
    /**
     * 角色接口
     */
    @Autowired
    private IRoleService roleServiceImpl;

    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(LogAction.class);

    /**
     * 分页开始条数
     */
    private int iDisplayStart;

    /**
     * 每页显示条数
     */
    private int iDisplayLength;

    private Log log;

    private String id;//日志Id

    /**
     * 获取最新十条系统日志
     *
     * @return json
     */
    public String getLastTenLog() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                List<Log> lList = logServiceImpl.listLastTenLog();
                String json = BaseTool.toJson(lList);
                out.print(json);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 获取日志列表
     *
     * @return json
     */
    public String getLogList() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                if (iDisplayLength == 0) {
                    iDisplayLength = -1;
                }
                int pageNum = (int) (Math.ceil(iDisplayStart / iDisplayLength)) + 1;
                /* 分页信息 */
                Page<Log> pageInfo = new Page<>(iDisplayLength);
                pageInfo.setPageNo(pageNum);
                pageInfo = logServiceImpl.pageByLog(pageInfo, log);
                int iTotalRecords = pageInfo.getTotalCount();
                int iTotalDisplayRecords = pageInfo.getTotalCount() < 0 ? 0 : pageInfo.getTotalCount();
                /* 得到结果 */
                List<Log> lList = pageInfo.getResult();
                /* 封装list */
                List<Map<String, Object>> logMapList = new ArrayList<>();
                if (lList != null && !lList.isEmpty() && lList.size() > 0) {
                    int i = (pageNum - 1) * iDisplayLength + 1;
                    for (Log l : lList) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("no", i);// 序号
                        map.put("id", l.getId());
                        map.put("userName", StringUtils.defaultString(l.getUserName(), ""));
                        map.put("loginName", StringUtils.defaultString(l.getLoginName(), ""));
                        map.put("module", StringUtils.defaultString(l.getModule(), ""));
                        Integer logType = l.getType();
                        String logTypeName = "";
                        if (logType != null) {
                            switch (logType) {
                                case 0:
                                    logTypeName = "未知";
                                    break;
                                case 1:
                                    logTypeName = "登录";
                                    break;
                                case 2:
                                    logTypeName = "操作";
                                    break;
                                case 3:
                                    logTypeName = "错误";
                                    break;
                                default:
                                    break;
                            }
                        }
                        map.put("logTypeName", logTypeName);
                        map.put("content", StringUtils.defaultString(l.getContent(), ""));
                        map.put("createTime", TimeTool.timestampToString(l.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                        logMapList.add(map);
                        i++;
                    }
                }
                //登录用户角色类型
                Integer roleType = PublicClass.getRoleTypeByLoginUser(loginUser, roleServiceImpl);
                Map<String, Object> jsonMap = new HashMap<>();
                jsonMap.put("roleType",roleType);
                jsonMap.put("iTotalRecords", iTotalRecords);
                jsonMap.put("iTotalDisplayRecords", iTotalDisplayRecords);
                jsonMap.put("aaData", logMapList);

                String json = BaseTool.toJson(jsonMap);
                out.print(json);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 删除日志
     *
     * @return 成功标识
     */
    public String deleteLog() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                Log log = logServiceImpl.getLogById(id);
                if (log != null) {
                    log.setIsDelete(1);
                    logServiceImpl.updateLog(log);
                    out.print(0);
                    //添加系统日志
                    String userName = loginUser.getUserName();
                    String nowTime = TimeTool.getNowTime();
                    String content = "用户：" + userName + "，于" + nowTime + " 删除系统日志：" + log.getContent() + "！";
                    PublicClass.addLog(userName, loginUser.getLoginName(), "系统日志", 2, content, logServiceImpl);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }


    public int getIDisplayStart() {
        return iDisplayStart;
    }

    public void setIDisplayStart(int iDisplayStart) {
        this.iDisplayStart = iDisplayStart;
    }

    public int getIDisplayLength() {
        return iDisplayLength;
    }

    public void setIDisplayLength(int iDisplayLength) {
        this.iDisplayLength = iDisplayLength;
    }

    public Log getLog() {
        return log;
    }

    public void setLog(Log log) {
        this.log = log;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}
